package cn.chinaunicom.sdsi.frm.workflow.task.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import cn.chinaunicom.sdsi.frm.workflow.task.dao.FlowCfgDao;

/**
 * 架增强activiti的配置表的访问层
 * 
 * @author liyh
 */
@Repository("flowCfgDao")
public class FlowCfgDaoImpl implements FlowCfgDao {

	private static final Log log = LogFactory.getLog(FlowCfgDaoImpl.class);

	/**
	 * Spring提供的JDBC工具
	 */
	private JdbcTemplate jdbcTemplate;

	/**
	 * 根据配置表得到无条件的URL路径
	 * 
	 * @param processDefinitionId
	 *            流程定义数据主键
	 * @param processDefinitionKey
	 *            流程定义key
	 * @param taskDefinitionKey
	 *            任务定义key
	 * @param taskTodo
	 *            是否为待办路径，反之为已办
	 * @return 路径结果集
	 */
	@Override
	public Map<String, Object> getTaskCustomUrl(String processDefinitionId, String processDefinitionKey,
			String taskDefinitionKey, boolean taskTodo) {

		String url = "";
		if (taskTodo) {
			url = "URL";
		} else {
			url = "HIST_URL";
		}
		Object[] params = new Object[3];
		params[0] = processDefinitionId;
		params[1] = processDefinitionKey;
		params[2] = taskDefinitionKey;

		/*
		 * 规则：默认获取环节配置配置定制的url 如果环节未定制，则获取类型配置中的URL
		 */
		StringBuilder sb = new StringBuilder("SELECT LINK.LINK_FLAG,");
		sb.append(" CASE WHEN LINK.").append(url).append(" IS NULL OR LENGTH(TRIM(LINK.").append(url)
				.append(")) < 1 THEN TYPE.").append(url).append(" ELSE LINK.").append(url).append(" END URL")
				.append(" FROM FLOW_CFG_TYPE TYPE INNER JOIN FLOW_CFG_LINK LINK")
				.append(" ON TYPE.FLOW_TYPE_ID = LINK.FLOW_TYPE_ID WHERE TYPE.FLOW_KEY_REV = ? AND TYPE.FLOW_KEY = ?")
				.append(" AND LINK.LINK_KEY = ? ORDER BY LINK.FLOW_LINK_ID");

		log.debug("begin to do query:" + sb.toString());

		List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toString(), params);
		if (list == null || list.size() == 0) {
			return null;
		}

		return list.get(0);
	}

	/**
	 * 根据流程定义获取首环节任务定义
	 * 
	 * @param processDefinitionId
	 *            流程定义数据主键
	 * @param processDefinitionKey
	 *            流程定义Key
	 * @return 发起环节流程编码
	 */
	@Override
	public String getStartTaskKey(String processDefinitionId, String processDefinitionKey) {

		Object[] params = new Object[2];
		params[0] = processDefinitionKey;
		params[1] = processDefinitionId;

		StringBuilder sb = new StringBuilder("SELECT LINK.LINK_KEY");
		sb.append(" FROM FLOW_CFG_LINK LINK INNER JOIN FLOW_CFG_TYPE TYPE")
				.append(" ON TYPE.FLOW_TYPE_ID = LINK.FLOW_TYPE_ID WHERE TYPE.FLOW_KEY = ?")
				.append(" AND TYPE.FLOW_KEY_REV = ? AND LINK.LINK_FLAG = 1 ORDER BY LINK.FLOW_LINK_ID");

		List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toString(), params);
		if (list == null || list.size() == 0) {
			return "";
		}
		String startTaskKey = String.valueOf(list.get(0).get("LINK_KEY"));

		return startTaskKey;
	}

	/**
	 * 据指定条件获取可到达环节信息
	 * 
	 * @param processDefinitionId
	 *            流程定义唯一信息
	 * @param processDefinitionKey
	 *            流程定义key
	 * @param taskDefinitionKey
	 *            任务定义key
	 * @param pathSelect
	 *            路径选择
	 * @param handleType
	 *            处理类型
	 * @return 包含目标环节定义key、目标环节名称及是否可撤回
	 */
	@Override
	public List<Map<String, Object>> getLinkIds(String processDefinitionId, String processDefinitionKey,
			String taskDefinitionKey, int pathSelect, int handleType) {

		Object[] params = new Object[5];
		params[0] = processDefinitionId;
		params[1] = processDefinitionKey;
		params[2] = taskDefinitionKey;
		params[3] = handleType;
		params[4] = pathSelect;

		// 20170310，不仅仅取目标环节定义KEY，额外附加目标环节 link_id，为处理可达结束环节数据准备
		// 20170418，考虑新老版本流程兼容并行，flow_cfg_type表加入定义ID对应字段
		StringBuilder sb = new StringBuilder("SELECT PATH.TO_FLOW_LINK_ID LINK_ID, TOLINK.LINK_KEY LINK_KEY,");
		sb.append(" CONCAT( CONCAT(TYPE.FLOW_NAME, '-'), TOLINK.LINK_NAME) LINK_NAME, PATH.WITHDRAW")
				.append(" FROM FLOW_CFG_LINK LINK LEFT JOIN FLOW_CFG_TYPE TYPE ON LINK.FLOW_TYPE_ID = TYPE.FLOW_TYPE_ID")
				.append(" LEFT JOIN FLOW_CFG_PATH PATH ON PATH.FLOW_LINK_ID = LINK.FLOW_LINK_ID")
				.append(" LEFT JOIN FLOW_CFG_LINK TOLINK ON TOLINK.FLOW_LINK_ID = PATH.TO_FLOW_LINK_ID")
				.append(" WHERE TYPE.FLOW_KEY_REV = ? AND TYPE.FLOW_KEY = ? AND LINK.LINK_KEY = ? AND PATH.HANDLE_TYPE = ?")
				.append(" AND PATH.PATH_SELECT = ? ORDER BY PATH.TO_FLOW_LINK_ID");

		List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toString(), params);
		if (list == null) {
			return new ArrayList<Map<String, Object>>();
		}

		return list;
	}

	/**
	 * 根据流程定义及环节定义查找
	 * 
	 * @param processDefinitionId
	 *            流程定义数据主键
	 * @param taskDefinitionKey
	 *            环节定义KEY
	 * @return 标签url集合
	 */
	@Override
	public List<Map<String, Object>> getTabUrls(String processDefinitionId, String taskDefinitionKey) {

		Object[] params = new Object[2];
		params[0] = processDefinitionId;
		params[1] = taskDefinitionKey;

		StringBuilder sb = new StringBuilder("SELECT TAB.NAME, TAB.URL, TAB.TAB_FLAG");
		sb.append(" FROM FLOW_CFG_TYPE TYPE INNER JOIN FLOW_CFG_LINK LINK ON TYPE.FLOW_TYPE_ID = LINK.FLOW_TYPE_ID")
				.append(" INNER JOIN FLOW_CFG_TAB TAB ON TAB.FLOW_LINK_ID = LINK.FLOW_LINK_ID WHERE STATUS = 1")
				.append(" AND TYPE.FLOW_KEY_REV = ? AND LINK.LINK_KEY = ? ORDER BY TAB.DIS_ORDER");

		List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toString(), params);
		if (list == null) {
			return new ArrayList<Map<String, Object>>();
		}

		return list;
	}

	/**
	 * 获取任务详细页面环节出行及按钮显隐配置
	 * 
	 * @param processDefinitionKey
	 *            流程定义Key
	 * @param taskDefinitionKey
	 *            任务定义Key
	 * @return 按钮显隐信息
	 */
	@Override
	public Map<String, Object> getLinkCfg(String processDefinitionKey, String taskDefinitionKey) {

		Object[] params = new Object[2];
		params[0] = processDefinitionKey;
		params[1] = taskDefinitionKey;

		StringBuilder sb = new StringBuilder("SELECT LINK.IS_COUNTERSIGN, LINK.BUTTON_BACK, LINK.BUTTON_TURN,");
		sb.append(" LINK.BUTTON_BREAK, LINK.BUTTON_QUICK FROM FLOW_CFG_LINK LINK INNER JOIN FLOW_CFG_TYPE TYPE ON")
				.append(" TYPE.FLOW_TYPE_ID = LINK.FLOW_TYPE_ID WHERE TYPE.FLOW_KEY = ? AND LINK.LINK_KEY = ?");

		List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toString(), params);
		if (list == null || list.size() == 0) {
			return null;
		}

		return list.get(0);
	}

	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}
